import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { message, Modal } from 'antd';
import { getUserInfo, isLoggedIn, getUserId } from '../utils/auth';
import  {http,host,port} from '../utils/host'
// 定义表白接口
interface Confession {
  _id: string;
  content: string;
  userId: string;
  username: string;
  likeCount: number;
  comments: Comment[];
  createdAt: string;
  // 其他表白相关字段
}

// 定义评论接口
interface Comment {
  _id: string;
  content: string;
  userId: string;
  username: string;
  createdAt: string;
  // 其他评论相关字段
}

// 定义分页接口
interface Pagination {
  page: number;
  limit: number;
  total: number;
}

const ConfessionWall: React.FC = () => {
  const navigate = useNavigate();
  // Add handleGoBack function here
  const handleGoBack = (): void => {
    navigate(-1);
  };
  const [confessions, setConfessions] = useState<Confession[]>([]);
  const [newConfession, setNewConfession] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [comments, setComments] = useState<Record<string, Comment[]>>({});
  const [newComment, setNewComment] = useState<string>('');
  const [activeCommentId, setActiveCommentId] = useState<string | null>(null);
  const [pagination, setPagination] = useState<Pagination>({ page: 1, limit: 10, total: 0 });
  // 跟踪已点赞的表白ID
  const [likedConfessions, setLikedConfessions] = useState<Set<string>>(new Set());
  const [showVipTip, setShowVipTip] = useState<boolean>(false);
  // 获取表白列表（带分页）
  const fetchConfessions = useCallback(async (): Promise<void> => {
    setLoading(true);
    try {
      const response = await axios.get<{
        confessions: Confession[];
        total: number;
      }>(`${http}${host}${port}/api/confessions`, {
        params: { page: pagination.page, limit: pagination.limit }
      });
      setConfessions(response.data.confessions || []);
      setPagination(prev => ({ ...prev, total: response.data.total }));
    } catch (error) {
      console.error('获取表白内容失败:', error);
      message.error(error.response?.data?.message || '获取表白内容失败，请重试');
    } finally {
      setLoading(false);
    }
  }, [pagination.page, pagination.limit]);

  // 组件挂载时获取表白列表
  useEffect(() => {
    fetchConfessions();
    // 设置定时刷新，每30秒更新一次列表
    const intervalId = setInterval(fetchConfessions, 30000);
    return () => clearInterval(intervalId);
  }, [fetchConfessions]);

  // 发布新表白
  const handlePublish = async (): Promise<void> => {
    // 检查用户是否已登录
    if (!isLoggedIn()) {
      message.warning('请先登录');
      return;
    }

    if (!newConfession.trim()) {
      message.warning('表白内容不能为空');
      return;
    }

    if (newConfession.length > 500) {
      message.warning('表白内容不能超过500字');
      return;
    }

    setLoading(true);
    try {
      const userId = getUserId();
      const response = await axios.post(`${http}${host}${port}/api/confessions`, {
        content: newConfession
      }, {
        headers: {
          'x-user-id': userId
        }
      });
      setConfessions([response.data, ...confessions]);
      setNewConfession('');
      setShowVipTip(false); // 发布成功，隐藏VIP提示
      message.success('发布表白成功');
    } catch (error) {
      console.error('发布表白失败:', error);
      console.log(error.response?.data);
      
      // 处理会员相关错误
      if (error.response?.status === 403) {
        setShowVipTip(true); // 显示VIP提示
      } else {
        message.error(error.response?.data?.message || '发布表白失败，请重试');
        setShowVipTip(false); // 其他错误，隐藏VIP提示
      }
    } finally {
      setLoading(false);
    }
  };

  // 隐藏VIP提示
  const handleCloseVipTip = (): void => {
    setShowVipTip(false);
  };

  // 表白点赞
  const handleLike = async (id: string): Promise<void> => {
    // 检查是否已经点赞
    if (likedConfessions.has(id)) {
      message.warning('每个用户只能点赞一次');
      return;
    }

    try {
      await axios.patch(`${http}${host}${port}/api/confessions/${id}/like`);
      setConfessions(confessions.map(confession => 
        confession._id === id ? { ...confession, likeCount: confession.likeCount + 1 } : confession
      ));
      // 添加到已点赞集合
      setLikedConfessions(new Set(likedConfessions).add(id));
      message.success('点赞成功');
    } catch (error) {
      console.error('点赞失败:', error);
      message.error(error.response?.data?.message || '点赞失败，请重试');
    }
  };

  // 显示评论输入框
  const handleShowComment = (id: string): void => {
    setActiveCommentId(id === activeCommentId ? null : id);
    setNewComment('');
  };

  // 提交评论
  const handleComment = async (id: string): Promise<void> => {
    if (!newComment.trim()) {
      message.warning('评论内容不能为空');
      return;
    }

    if (newComment.length > 200) {
      message.warning('评论内容不能超过200字');
      return;
    }

    try {
      const response = await axios.post(`${http}${host}${port}/api/confessions/${id}/comment`, {
        content: newComment
      });
      setConfessions(confessions.map(confession => 
        confession._id === id ? { ...confession, comments: response.data.comments } : confession
      ));
      setActiveCommentId(null);
      message.success('评论成功');
    } catch (error) {
      console.error('评论失败:', error);
      message.error(error.response?.data?.message || '评论失败，请重试');
    }
  };

  // 分页处理
  const handlePageChange = (newPage: number): void => {
    setPagination(prev => ({ ...prev, page: newPage }));
  };

  // 跳转到会员充值页面
  const handleVipRecharge = (): void => {
    // 这里假设会员充值页面的路由是/vip
    navigate('/vip');
  };

  // 样式定义
  const styles = {
    container: {
      maxWidth: '800px',
      margin: '0 auto',
      padding: '20px',
      height: '100vh',
      overflowY: 'auto',
      boxSizing: 'border-box'
    },
    title: {
      textAlign: 'center',
      fontSize: '24px',
      marginBottom: '20px',
      color: '#333',
    },
    publishArea: {
      backgroundColor: '#f9f9f9',
      padding: '20px',
      borderRadius: '8px',
      marginBottom: '30px',
    },
    textarea: {
      width: '100%',
      height: '100px',
      padding: '10px 16px',
      borderRadius: '4px',
      border: '1px solid #ddd',
      resize: 'none',
      marginBottom: '10px',
      fontSize: '14px',
      boxSizing: 'border-box',
    },
    publishButton: {
      backgroundColor: '#1890ff',
      color: 'white',
      border: 'none',
      padding: '8px 16px',
      borderRadius: '4px',
      cursor: 'pointer',
      fontSize: '14px',
    },
    confessionsList: {
      marginTop: '20px',
    },
    confessionCard: {
      backgroundColor: 'white',
      padding: '20px',
      borderRadius: '8px',
      boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
      marginBottom: '15px',
    },
    confessionContent: {
      fontSize: '16px',
      lineHeight: '1.6',
      marginBottom: '15px',
    },
    metaInfo: {
      display: 'flex',
      justifyContent: 'space-between',
      fontSize: '12px',
      color: '#666',
      marginBottom: '10px',
    },
    actions: {
      display: 'flex',
      gap: '15px',
      fontSize: '14px',
    },
    actionButton: {
      border: 'none',
      background: 'none',
      cursor: 'pointer',
      color: '#666',
      display: 'flex',
      alignItems: 'center',
      gap: '5px',
    },
    commentsSection: {
      marginTop: '15px',
      paddingTop: '15px',
      borderTop: '1px solid #eee',
    },
    commentInput: {
      display: 'flex',
      gap: '10px',
      marginBottom: '15px',
    },
    commentTextarea: {
      flex: 1,
      height: '60px',
      padding: '10px 16px',
      borderRadius: '4px',
      border: '1px solid #ddd',
      resize: 'none',
      fontSize: '14px',
      boxSizing: 'border-box',
    },
    commentsList: {
      marginTop: '15px',
    },
    comment: {
      padding: '10px',
      backgroundColor: '#f9f9f9',
      borderRadius: '4px',
      marginBottom: '10px',
    },
    commentContent: {
      fontSize: '14px',
      marginBottom: '5px',
    },
    commentTime: {
      fontSize: '12px',
      color: '#999',
    },
    pagination: {
      display: 'flex',
      justifyContent: 'center',
      marginTop: '30px',
      gap: '10px',
    },
    pageButton: {
      padding: '5px 10px',
      border: '1px solid #ddd',
      borderRadius: '4px',
      cursor: 'pointer',
    },
    loading: {
      textAlign: 'center',
      padding: '50px',
      color: '#666',
    }
  };

  return (
    <div style={styles.container}>
      <div style={styles.backButton} onClick={handleGoBack}>返回</div>
      <h1 style={styles.title}>匿名表白墙</h1>

      {/* 发布区域 */}
      <div style={styles.publishArea}>
        <textarea
          style={styles.textarea}
          placeholder="写下你的匿名表白...（最多500字）"
          value={newConfession}
          onChange={(e) => setNewConfession(e.target.value)}
          maxLength={500}
        />
        <div style={styles.buttonContainer}>
          <button
            style={styles.publishButton}
            onClick={handlePublish}
            disabled={loading || !newConfession.trim()}
          >
            {loading ? '发布中...' : '发布'}
          </button>
          {showVipTip && (
            <div style={styles.vipTip}>
              <div style={styles.vipTipContent}>
                <p style={styles.vipTipText}>今日免费次数已用完</p>
                <button
                  style={styles.vipTipButton}
                  onClick={handleVipRecharge}
                >
                  立即充值
                </button>
                <button
                  style={styles.vipTipClose}
                  onClick={handleCloseVipTip}
                >
                  ×
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 表白列表区域 */}
      <div style={styles.confessionsList}>
        {loading ? (
          <div style={styles.loading}>加载中...</div>
        ) : confessions.length > 0 ? (
          <> 
            {confessions.map((confession) => (
              <div key={confession._id} style={styles.confessionCard}>
                <p style={styles.confessionContent}>{confession.content}</p>
                <div style={styles.metaInfo}>
                  <span>{new Date(confession.publishTime).toLocaleString()}</span>
                </div>
                <div style={styles.actions}>
                  <button
                    style={styles.actionButton}
                    onClick={() => handleLike(confession._id)}
                    disabled={likedConfessions.has(confession._id)}
                  >
                    <span style={{ color: likedConfessions.has(confession._id) ? '#ff4d4f' : '#666' }}>❤️</span> {confession.likeCount}
                  </button>
                  <button
                    style={styles.actionButton}
                    onClick={() => handleShowComment(confession._id)}
                  >
                    <span>💬</span> 评论 ({confession.comments.length})
                  </button>
                </div>

                {/* 评论区域 */}
                {activeCommentId === confession._id && (
                  <div style={styles.commentsSection}>
                    <div style={styles.commentInput}>
                      <textarea
                        style={styles.commentTextarea}
                        placeholder="写下你的评论...（最多200字）"
                        value={newComment}
                        onChange={(e) => setNewComment(e.target.value)}
                        maxLength={200}
                      />
                      <button
                        style={styles.publishButton}
                        onClick={() => handleComment(confession._id)}
                      >
                        发送
                      </button>
                    </div>
                  </div>
                )}

                {/* 显示评论列表 */}
                {confession.comments.length > 0 && (
                  <div style={styles.commentsList}>
                    {confession.comments.slice(0, 3).map((comment, index) => (
                      <div key={index} style={styles.comment}>
                        <p style={styles.commentContent}>{comment.content}</p>
                        <div style={styles.commentTime}>
                          {new Date(comment.publishTime).toLocaleString()}
                        </div>
                      </div>
                    ))}
                    {confession.comments.length > 3 && (
                      <div style={{ textAlign: 'center', fontSize: '12px', color: '#666' }}>
                        显示前3条评论，共{confession.comments.length}条
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}

            {/* 分页控件 */}
            <div style={styles.pagination}>
              <button
                style={styles.pageButton}
                onClick={() => handlePageChange(pagination.page - 1)}
                disabled={pagination.page <= 1}
              >
                上一页
              </button>
              <span>第{pagination.page}页 / 共{Math.ceil(pagination.total / pagination.limit)}页</span>
              <button
                style={styles.pageButton}
                onClick={() => handlePageChange(pagination.page + 1)}
                disabled={pagination.page >= Math.ceil(pagination.total / pagination.limit)}
              >
                下一页
              </button>
            </div>
          </>
        ) : (
          <div style={styles.loading}>暂无表白内容，快来发布第一条表白吧！</div>
        )}
      </div>


      </div>
  );
};

export default ConfessionWall;

const styles = {
  backButton: {
    margin: '10px 0',
    padding: '8px 16px',
    backgroundColor: '#f0f0f0',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    alignSelf: 'flex-start'
  },
  title: {
    textAlign: 'center',
    fontSize: '24px',
    marginBottom: '20px',
    color: '#333',
  },
  publishArea: {
    backgroundColor: '#f9f9f9',
    padding: '20px',
    borderRadius: '8px',
    marginBottom: '30px',
  },
  textarea: {
    width: '100%',
    height: '100px',
    padding: '10px 16px',
    borderRadius: '4px',
    border: '1px solid #ddd',
    resize: 'none',
    marginBottom: '10px',
    fontSize: '14px',
    boxSizing: 'border-box',
  },
  buttonContainer: {
    display: 'flex',    
    justifyContent: 'center',
    alignItems: 'center',
  },
  publishButton: {
    backgroundColor: '#1890ff',
    color: 'white',
    border: 'none',
    padding: '8px 16px',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
  },
  vipTip: {
    position: 'relative',
    marginLeft: '15px',
  },
  vipTipContent: {
    position: 'absolute',
    right: '0',
    top: '100%',
    marginTop: '8px',
    width: '220px',
    padding: '15px',
    backgroundColor: '#fff',
    borderRadius: '8px',
    border: '1px solid #eee',
    boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
    zIndex: '100',
    display: 'flex',
    flexDirection: 'column',
    // 添加小三角
    '&::before': {
      content: '""',
      position: 'absolute',
      top: '-6px',
      right: '15px',
      width: '12px',
      height: '12px',
      backgroundColor: '#fff',
      border: '1px solid #eee',
      borderBottom: 'none',
      borderRight: 'none',
      transform: 'rotate(45deg)',
      zIndex: '1'
    }
  },
  vipTipText: {
    margin: '0 0 12px 0',
    fontSize: '14px',
    color: '#333',
    fontWeight: '500',
    textAlign: 'center',
  },
  vipTipButton: {
    padding: '8px 16px',
    backgroundColor: '#ff7a45',
    color: '#fff',
    border: 'none',
    borderRadius: '20px',
    cursor: 'pointer',
    fontSize: '14px',
    fontWeight: 'bold',
    marginBottom: '8px',
    textAlign: 'center',
    transition: 'all 0.3s ease',
    '&:hover': {
      backgroundColor: '#ff5252',
      transform: 'translateY(-2px)',
      boxShadow: '0 4px 8px rgba(255, 122, 69, 0.3)',
    },
    '&:active': {
      transform: 'translateY(0)',
      boxShadow: '0 2px 4px rgba(255, 122, 69, 0.2)',
    },
  },
  vipTipClose: {
    position: 'absolute',
    top: '8px',
    right: '8px',
    width: '20px',
    height: '20px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#f5f5f5',
    border: 'none',
    borderRadius: '50%',
    cursor: 'pointer',
    fontSize: '14px',
    color: '#999',
    transition: 'all 0.2s ease',
    '&:hover': {
      backgroundColor: '#e0e0e0',
      color: '#666',
    },
  },
  confessionsList: {
    marginTop: '20px',
  },
  confessionCard: {
    backgroundColor: 'white',
    padding: '20px',
    borderRadius: '8px',
    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
    marginBottom: '15px',
  },
  confessionContent: {
    fontSize: '16px',
    lineHeight: '1.6',
    marginBottom: '15px',
  },
  metaInfo: {
    display: 'flex',
    justifyContent: 'space-between',
    fontSize: '12px',
    color: '#666',
    marginBottom: '10px',
  },
  actions: {
    display: 'flex',
    gap: '15px',
    fontSize: '14px',
  },
  actionButton: {
    border: 'none',
    background: 'none',
    cursor: 'pointer',
    color: '#666',
    display: 'flex',
    alignItems: 'center',
    gap: '5px',
  },
  commentsSection: {
    marginTop: '15px',
    paddingTop: '15px',
    borderTop: '1px solid #eee',
  },
  commentInput: {
    display: 'flex',
    gap: '10px',
    marginBottom: '15px',
  },
  commentTextarea: {
    flex: 1,
    height: '60px',
    padding: '10px 16px',
    borderRadius: '4px',
    border: '1px solid #ddd',
    resize: 'none',
    fontSize: '14px',
    boxSizing: 'border-box',
  },
  commentsList: {
    marginTop: '15px',
  },
  comment: {
    padding: '10px',
    backgroundColor: '#f9f9f9',
    borderRadius: '4px',
    marginBottom: '10px',
  },
  commentContent: {
    fontSize: '14px',
    marginBottom: '5px',
  },
  commentTime: {
    fontSize: '12px',
    color: '#999',
  },
  pagination: {
    display: 'flex',
    justifyContent: 'center',
    marginTop: '30px',
    gap: '10px',
  },
  pageButton: {
    padding: '5px 10px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    cursor: 'pointer',
  },
  loading: {
    textAlign: 'center',
    padding: '50px',
    color: '#666',
  }
};